import { Button, Drawer, DrawerProps, Form, Input, Spin, message } from "antd"
import { useForm } from "antd/es/form/Form";
import { ISys, useAddSys, useUpdateSys } from "../../../service/syscontroller";
import { QueryObserverResult, RefetchOptions, RefetchQueryFilters } from "react-query";
import { IFormRef, ILawsRef, IPage, IRoleRestFillRefHandler, ISelectMutiRef } from "../../../types";
import { memo, useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react';
import { IUploadImgRefHandler, UploadImage } from "../../../components/upload-img";
import { RolePermissionSelect } from "../../../components/role-select";
import UnitTreeSelect from "../../../components/unit-tree-select";
import SqUnitSelectMu from "../../../components/squnit-select-multiple"
/**
 * 添加用户-修改用户,以及查看用户基本信息的表单
 */

type SysFormProps = {
    sys?: ISys;
    onRef: React.MutableRefObject<IFormRef | undefined>,
    refetch?: <TPageData>(options?: (RefetchOptions & RefetchQueryFilters<TPageData>) | undefined) => Promise<QueryObserverResult<IPage<ISys>, unknown>>
    unitRef: React.MutableRefObject<IRoleRestFillRefHandler | undefined>,
    onCloseHandler: (status: boolean) => void;
} & DrawerProps

const SysForm = ({ sys, unitRef, onRef, onCloseHandler, refetch, ...props }: SysFormProps) => {
    const [form] = useForm();
    const roleId = useRef<number>()
    const unitCheckRef = useRef<{ unitId: string, unitName: string }>();
    const sysImageRef = useRef<IUploadImgRefHandler>();
    const sysRoleSelectRef = useRef<IRoleRestFillRefHandler>();
    const sqUnitRef = useRef<ISelectMutiRef>();
    /**
     * 上传头像回调
     * @param sysAvater
     */
    const getUrlHandler = (sysAvater: string) => {
        form.setFieldValue("sysAvater", sysAvater)
    };
    /**
     * 角色下拉选中回调
     */
    const roleChange = (value: number) => {
        form.setFieldValue("sysRoleId", value)
    };

    /**
     * 更新方法
     */
    const updateHandler = async () => {
        //校验表单
        const isPass = await form.validateFields();
        if (!isPass || !sys?.sysId) {
            return;
        }
        const values = form.getFieldsValue();
        await updateSysMutation({
            sysId: sys?.sysId,
            ...values
        });
        refetch?.();
        onCloseHandler(false);
        form.resetFields();
        sysRoleSelectRef.current?.rest();
        sysImageRef.current?.rest();
        sqUnitRef.current?.rest();
    }

    /**
     * 保存方法
     */
    const saveHandler = async () => {
        //校验表单
        const isPass = form.validateFields();
        if (!isPass) {
            return;
        }
        const values = await form.getFieldsValue();
        await addSysMutation({ unitId: unitCheckRef.current?.unitId, ...values });
        refetch?.();
        onCloseHandler(false);
        form.resetFields();
        sysRoleSelectRef.current?.rest();
        sysImageRef.current?.rest();
        sqUnitRef.current?.rest();
    }

    useEffect(() => {
        if (sys) {
            form.setFieldsValue({
                unitName: sys ? sys.unitName : unitRef.current?.getData?.().name,
                sysName: sys.sysName,
                sysNickName: sys.sysNickName,
                sysRoleId: sys.sysRoleId,
                phone: sys.phone
            });
            sysRoleSelectRef.current?.fill(sys.sysRoleId);
            sqUnitRef.current?.fill(sys?.sqUnitId ? JSON.parse(sys?.sqUnitId) : [])
        }
    }, [unitRef, props.open]);

    /**
     * 向外暴露表单的保存和修改
     */
    useImperativeHandle(onRef, () => ({
        reset: () => {
            form.resetFields();
            sysRoleSelectRef.current?.rest();
            sysImageRef.current?.rest();
        },
        save: async () => {
            updateHandler();
        },
        update: async () => {

        },
    }));

    const [checkUnitId, setCheckUnitId] = useState<string | undefined>(sys?.unitId)
    /**
     * 获取选中的单位
     */
    const getCheckUnit = useCallback((unitId: string, unitName: string) => {
        unitCheckRef.current = { unitId, unitName }
        setCheckUnitId(unitId);
        form.setFieldValue("unitId", unitId);
    }, [])
    /**
     * !添加用户接口Hook
     */
    const { mutateAsync: addSysMutation, isLoading: addIsLoading } = useAddSys();
    /**
     * !修改用户接口Hook
     */
    const { mutateAsync: updateSysMutation, isLoading: UIsLoading } = useUpdateSys();

    const sqSelectHandlerChange = useCallback((val: string[]) => {
        if (val.length > 0) {
            form.setFieldValue("sqUnitId", JSON.stringify(val))
        } else {
            form.setFieldValue("sqUnitId", "")
        }
    }, [])

    return (<Drawer
        title={sys ? '修改用户' : '添加用户 '}
        placement="right"
        width={'35rem'}
        closable={true}
        onClose={() => onCloseHandler(false)}
        forceRender={true}
        open={props.open} footer={
            <>
                {
                    sys ? (
                        <Button onClick={() => { updateHandler(); }}>
                            修改
                        </Button>
                    ) : (
                        <Button onClick={() => { saveHandler(); }}>
                            保存
                        </Button>
                    )
                }
            </>
        }
    >
        <Spin spinning={addIsLoading || UIsLoading}>
            <Form
                form={form}
                labelCol={{ span: 5 }}
                wrapperCol={{ span: 19 }}
                initialValues={{
                }}
            >
                <Form.Item label={'所属单位'} name={'unitName'} >
                    <UnitTreeSelect getCheckUnit={getCheckUnit} initUnitName={sys?.unitName} />
                </Form.Item>
                <Form.Item label={'所属社区'} name={'sqUnitId'}>
                    <SqUnitSelectMu handleChange={sqSelectHandlerChange} onRef={sqUnitRef} unitId={checkUnitId || ''} sqUnitId={sys?.sqUnitId ? JSON.parse(sys?.sqUnitId) : []} />
                </Form.Item>
                <Form.Item label={'用户名称'} name={'sysName'} rules={[{ required: true, message: '用户名称不能为空' }]}>
                    <Input />
                </Form.Item>
                <Form.Item label={'用户密码'} name={'sysPassword'} rules={[{ required: sys?.sysId ? false : true, message: '用户密码不能为空' }]}>
                    <Input />
                </Form.Item>
                <Form.Item label={'用户昵称'} name={'sysNickName'}>
                    <Input />
                </Form.Item>
                <Form.Item label={'手机号码'} name={'phone'}>
                    <Input />
                </Form.Item>

                <Form.Item label={'用户头像'} name={'sysAvater'}>
                    <UploadImage getUrlHandler={getUrlHandler} maxCount={1} onRef={sysImageRef} />
                </Form.Item>
                <Form.Item label={'用户角色'} name={'sysRoleId'} rules={[{ required: true, message: '用户角色不能为空' }]}>
                    <RolePermissionSelect handleChange={roleChange} onRef={sysRoleSelectRef} />
                </Form.Item>

            </Form>
        </Spin>
    </Drawer >
    );
}

export default memo(SysForm)